<?php

namespace App\Services\CloseUnpaidStorm;

use App\Models\GoldRecord;
use Carbon\Carbon;
use App\Models\User;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class CloseUnpaidStorm
{
	protected ?User $user = null;

	protected string $unpaidCacheId;

    protected ?GoldRecord $record = null;

	public function __construct($uid, $unpaidCacheId)
	{
		$user = User::find($uid);
		$this->user = $user ?? null;
		$this->unpaidCacheId = $unpaidCacheId;
        $this->record = GoldRecord::find(Redis::hGet($unpaidCacheId, 'gold_record_id'));
	}

	protected function canBeClosed(): bool
	{
		$isPaying = Redis::hGet($this->unpaidCacheId, 'is_paying');
		$isPaid = Redis::hGet($this->unpaidCacheId, 'is_paid');
		
		$isExamine = Redis::hGet($this->unpaidCacheId, 'is_examine');

        if (!$this->record) return false;
		if ($isPaying) return false;
		if ($isPaid) return false;
		
		if ($isExamine) return false;

		return true;
	}

	protected function fineRecordBeans()
	{

        if (! cs('storm')->is_overcome_pay_fine) return;
        $record = $this->record;

        $paidBeans = $record->pay_gold_beans;

        if (empty($paidBeans)) return;

        $rid = $record->gold_round_id;
        $pid = $record->gold_product_id;

        $data = [
            'datetime' => Carbon::now()->toDateTimeString(),
            'gold_round_id' => $rid,
            'gold_product_id' => $pid,
        ];
		account_beans($this->user)->minusOvertimeFineBeans($paidBeans, $data);
	}

	protected function restoreSelling()
	{
        $this->record->update(['closed_at' => Carbon::now()]);
        if($this->record->is_del == 0){
        	$this->user->closeRecordFromUnpaidCache($this->unpaidCacheId);
        }
		
	}

	public function close()
	{
		if (!$this->user) return;

		if (! $this->canBeClosed()) return;
		//$this->fineRecordBeans();
		$this->restoreSelling();
	}
}
